/*
 * @Author: liaoxing
 * @Date: 2021-08-13 10:21:54
 * @LastEditors: liaoxing
 * @LastEditTime: 2021-08-13 11:57:38
 * @Description: file content
 * @FilePath: \bigScreen\src\dev-core\router\index.js
 */
// import Vue from 'vue'
import vueRouter from 'vue-router'
import initRoutes from './initRouter'
import routerHelper from '../utils/routerHelper'
import sessionStorage from '@base/utils/sessionStorage'

// Vue.use(vueRouter)

const originalPush = vueRouter.prototype.push
vueRouter.prototype.push = function push(location, onResolve, onReject) {
if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const router = new vueRouter({
  mode: process.env.NODE_ENV === 'production' ? 'history' : 'hash',
  routes: initRoutes
})
// let init = false
router.beforeEach(async (to, from, next) => {
  // console.log(router)
  // console.log(to)
  let token = sessionStorage.get('token')
  // if (process.env.NODE_ENV === 'development' && !token) {
  //   token = '999999'
  // }
  // console.log(token)
  if (token === null || !token) { // 判断是否有登录态，如果没有则报错，并导航回登录页面
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  } else { // 已有登录态，直接进入页面
    if (to.path === '/login') {
      next()
    } else {
      if (to.name) {
        next()
      } else {
        await routerHelper(router)
        next(to.path)
      }
    }
  }
})

// routerHelper(router)

export default router
